#include <iostream>
#include <pthread.h>
#include <queue>
#include <unistd.h>
using namespace std;

// 使用阻塞队列+条件变量实现生产者-消费者模型
#define MAX_SIZE 10
queue<int> q;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER; //
pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;  //

// 修改 producer 函数的参数为 void*
void producer(void *arg)
{
    int *data = (int *)arg;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        // 当队列满的时候通知consumer可以消费了
        while (q.size() == MAX_SIZE)
        {
            // 当队列的时候通知consumer可以消费了
            pthread_cond_signal(&not_empty);
            // 等待队列不满的条件变量
            pthread_cond_wait(&not_full, &mutex);
        }
        // 当队列不满的时候生产数据
        q.push((*data));
        cout << "producer: " << *data << endl;
        (*data)++;
        sleep(1);

        pthread_mutex_unlock(&mutex);
    }
}

void consumer()
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (q.empty())
        {
            // 通知生产者可以生产了
            pthread_cond_signal(&not_full);
            // 等待队列不为空的条件变量
            pthread_cond_wait(&not_empty, &mutex);
        }
        // 当队列不为空的时候消费
        cout << "consumer: " << q.front() << endl;
        q.pop();
        sleep(1);
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    int data = 0;
    pthread_t t1, t2;
    // 正确传递参数
    pthread_create(&t1, NULL, (void *(*)(void *))producer, &data);
    pthread_create(&t2, NULL, (void *(*)(void *))consumer, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}